package org.apache.maven.plugins.mergeproperties;

import java.util.regex.Pattern;

import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.logging.Log;



/**
 * Represent a pattern to apply on a value.
 *
 */
public class CheckRegExp {

	/**
	 * Regexp to test on the value
	 * @parameter
	 * @required
	 */
	private String regExp;
	
	
	/**
	 * needToFind if we need to find the regExp into the value
	 * @parameter default-value="true"
	 * 
	 */
	private boolean needToFind;
	
	
	
	/**
	 * Level of the check:
	 * warn  : print a warn into the console 
	 * error : stop the execution of the plugin
	 * 
	 * @parameter default-value("warn")
	 * 
	 */
	private String level;
	
		
	protected Pattern pattern;
	
	
	
	
	/**
	 * Check the value against the regex
	 * @param log the logger
	 * @param key the key
	 * @param value the value to test
	 * @throws MojoExecutionException if value is not compilant with teh regex
	 */
	void checkValue(Log log, String fileName, String key, String value) throws MojoFailureException {
		
		if (pattern == null)
			pattern = Pattern.compile(regExp);
		
		String msg = null;
		
		boolean matching = pattern.matcher(value).find();
		
		log.debug("Tested Value = " + value + " Pattern : " + pattern.pattern() + " Matching ? " + matching);
		
		// if data is  present and don't have to be
		if (matching && !needToFind)			
			msg = "[FAIL]: the pattern (" + pattern.pattern()+") match and it does'nt!."; 				
		
		
		// if data is not present and have to be
		if (!matching && needToFind)
			msg = "[FAIL]: the pattern (" + pattern.pattern() + ") doesn't match and it do."; 				
		
		if (msg != null) {
			
			msg = "[fileName=" + fileName + ", key=" + key + ", value=" + value + "] " + msg;  
			
			if (level.equalsIgnoreCase("warn")) {
				log.warn(msg);							
			}
			
			if (level.equalsIgnoreCase("error")) {
				log.error(msg);	
				throw new MojoFailureException(msg); 
			}
		}
		
	}
	
	
}
